package com.cyanite.playlv2;

import com.cyanite.playlv2.util.NotificationsUtil;
import com.cyanite.playlv2.widget.DataBaseAdapter;
import com.cyanite.playlv2api.PlayLv2Api;
import com.cyanite.playlv2api.types.Response;
import com.cyanite.playlv2api.util.ConstantsUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class TripCreateThemeActivity extends Activity   {

    private StateHolder mStateHolder;
    private ProgressDialog mDlgProgress;
	private EditText mThemeTitle;
	private Spinner  mSpinnerTheme;
	private AutoCompleteTextView mTripAddress;
	private DatePicker mDatePicker;
	private Calendar mCalendar;
	private int mYear = 0;
	private int mMonth = 0;
	private int mDay = 0;

	private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };

	public void onCreate(Bundle savedInstanceState)	{
		super.onCreate(savedInstanceState);
		registerReceiver(mLoggedOutReceiver, new IntentFilter(PlayLv2.INTENT_ACTION_LOGGED_OUT));
		setTheme(android.R.style.Theme);
        setContentView( R.layout.trip_create_theme_activity );
        setTitle(getString(R.string.trip_create_theme_activity_label));

        mStateHolder = new StateHolder();
        ensureUi();
	}

	private void ensureUi()    {
	    mDatePicker = (DatePicker)findViewById(R.id.themeDatepicker);
        mCalendar = Calendar.getInstance();
        mYear = mCalendar.get(Calendar.YEAR);
        mMonth = mCalendar.get(Calendar.MONTH);
        mDay = mCalendar.get(Calendar.DAY_OF_MONTH);
        mDatePicker.init(mYear,mMonth,mDay, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)    {
                monthOfYear++;
                int myear = mCalendar.get(Calendar.YEAR);
                int mmon = mCalendar.get(Calendar.MONTH) + 1;
                int mday = mCalendar.get(Calendar.DAY_OF_MONTH);
                Date currentDate = new Date(mCalendar.get(Calendar.YEAR), 
                        mCalendar.get(Calendar.MONTH)+1, mCalendar.get(Calendar.DAY_OF_MONTH));
                if (currentDate.compareTo(new Date(year,monthOfYear,dayOfMonth)) > 0)   {
                    Toast.makeText(TripCreateThemeActivity.this, getString(R.string.trip_create_invalidate_date_note), Toast.LENGTH_LONG).show();
                    mDatePicker.updateDate(myear, mmon-1, mday);
                    return;
                }
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
            }
        });

        String shopping = this.getString(R.string.trip_shopping);
        String entertainment = this.getString(R.string.trip_entertainment);
        String gathering = this.getString(R.string.trip_gathering);
        String food = this.getString(R.string.trip_food);
        String sport = this.getString(R.string.trip_sport);
        final String[]  mThemes = {shopping, entertainment, gathering, food, sport};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, mThemes);
        mSpinnerTheme = (Spinner)findViewById(R.id.spinnerType);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinnerTheme.setAdapter(adapter);
        mSpinnerTheme.setOnItemSelectedListener(new Spinner.OnItemSelectedListener()    {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
                mStateHolder.setCategoryId(position+2);
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });

        mThemeTitle = (EditText)findViewById(R.id.etThemeTitle);
        mThemeTitle.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});

        Button btnCreate = (Button)findViewById(R.id.btnCreate);
        btnCreate.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v){
                popUpAlertDialog(TripCreateThemeActivity.this, 
                        TripCreateThemeActivity.this.getString(R.string.trip_create_theme_note));
            }
        });
        ArrayList<String> list = (((PlayLv2) getApplication())).getDBList();
        if (list == null) {
            try {
                DataBaseAdapter db = new DataBaseAdapter(this);
                db.open();            
                list = new ArrayList<String>();
                db.getCityList(list);
                db.getPlacesList(list);               
                db.close();
            } catch (Exception ex)    {
            }
        }
        mTripAddress = (AutoCompleteTextView)findViewById(R.id.tvAddressOrHope);
        ArrayAdapter<String> adapterAddr = new ArrayAdapter<String>(this, 
                android.R.layout.simple_dropdown_item_1line, list);
        mTripAddress.setAdapter(adapterAddr);
	}

	public void popUpAlertDialog(Context context, String str)   {
        AlertDialog dlg = new AlertDialog.Builder(this)
        .setTitle(context.getString(R.string.trip_alert))
        .setMessage(str)
        .setPositiveButton(context.getString(R.string.ok),
        new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int whichButton)    {
                String title = mThemeTitle.getText().toString();
                int year  = mDatePicker.getYear();
                int month = mDatePicker.getMonth()+1;
                int day = mDatePicker.getDayOfMonth();
                String endpoint  = mTripAddress.getText().toString();
                String date  = String.format(TripCreateThemeActivity.this.getString(R.string.trip_date), year, month, day);
                if( title.length() != 0 ){
                    mStateHolder.startTaskCreateTrip( TripCreateThemeActivity.this,
                                                                                new String[] {
                                                                                        title,
                                                                                        "",
                                                                                        endpoint,
                                                                                        date,
                                                                                        ConstantsUtils.TripTypeConsts.tripTypeS[mStateHolder.getCategoryId()],
                                                                                        "1" });

                }   else if(title.equalsIgnoreCase("")) {
                    Toast.makeText(TripCreateThemeActivity.this,TripCreateThemeActivity.this.getString(R.string.trip_title).substring(0, 4)+TripCreateThemeActivity.this.getString(R.string.trip_alert_info), Toast.LENGTH_LONG).show();
                }
            }
        }).setNegativeButton(context.getString(R.string.cancel),
        new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int whichButton){
            }
        }).create();
        dlg.show();
    }

	@Override
    public void onPause() {
        super.onPause();
        stopProgressBar();
    }

	@Override
    public void onDestroy() {
        super.onDestroy();
        stopProgressBar();
        unregisterReceiver(mLoggedOutReceiver);
    }

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (keyCode == KeyEvent.KEYCODE_BACK)   {
            startActivity(new Intent(TripCreateThemeActivity.this, TripCreateMainActivity.class));
            finish();
            return true;
        }
        return false;
    }

	private void startProgressBar() {
        if (mDlgProgress == null) {
            mDlgProgress = ProgressDialog.show(this, null, 
                    getResources().getString(R.string.trip_create_progress_bar_message));
        }
        mDlgProgress.show();
    }

    private void stopProgressBar() {
        if (mDlgProgress != null) {
            mDlgProgress.dismiss();
            mDlgProgress = null;
        }
    }

	private void createTripTaskComplete(Response response, Exception ex) {
        stopProgressBar();
        if (response != null && Integer.valueOf(response.getValue()) > 0) {
            Toast.makeText(TripCreateThemeActivity.this, getString(R.string.trip_create_success_toast),
                    Toast.LENGTH_LONG).show();

            // now loop into add follows activity
            Intent intent = new Intent(TripCreateThemeActivity.this, AddFollowsActivity.class);
            intent.putExtra(AddFollowsActivity.EXTRA_TRIP_ID, response.getValue());
            startActivity(intent);
            finish();
        }   else {
            // Error, let them hang out here.
            NotificationsUtil.ToastReasonForFailure(this, ex);
        }
    }

	private static class CreateTripTask extends AsyncTask<Void, Void, Response> {

        private TripCreateThemeActivity mActivity;
        private String[] mParams;
        private Exception mReason;
        private PlayLv2 mPlayLv2;

        public CreateTripTask(TripCreateThemeActivity activity,
                                              String[] params) {
            mActivity = activity;
            mParams = params;
            mPlayLv2 = (PlayLv2) activity.getApplication();
        }

        @Override
        protected void onPreExecute() {
            mActivity.startProgressBar();
        }

        @Override
        protected Response doInBackground(Void... params) {
            try {
                PlayLv2Api playlv2api = mPlayLv2.getPlayLv2Api();
                Response response = playlv2api.createTrip(mParams[0], // title
                                                                mParams[1], // startpoint
                                                                mParams[2], // endpoint
                                                                mParams[3], // starttime,
                                                                mParams[4], // type
                                                                mParams[5]);  // days
                if (response == null)   response = new Response();
                return response;
                    } catch (Exception ex) {
                mReason = ex;
                return null;
            }
        }

        @Override
        protected void onPostExecute(Response response) {
            if (mActivity != null) {
                mActivity.createTripTaskComplete(response, mReason);
            }
        }

        @Override
        protected void onCancelled() {
            if (mActivity != null) {
                mActivity.createTripTaskComplete(null, mReason);
            }
        }
    }

    private static class StateHolder {

        private CreateTripTask mTaskCreateTrip;
        private int mCategoryId;

        public StateHolder() {
        }

        public int getCategoryId()   {
            return mCategoryId;
        }
        
        public void setCategoryId(int id)   {
            mCategoryId = id;
        }

        public void startTaskCreateTrip(TripCreateThemeActivity activity, String[] params) {
            mTaskCreateTrip = new CreateTripTask(activity, params);
            mTaskCreateTrip.execute();
        }
    }
}
